#include "CenterHappyFarmManager.h"
#include "StringConverter.h"
#include "ResourceManager.h"
#include "Database/DatabaseEnv.h"
#include "StringConverter.h"
#include "json/json.h"
#include "NGLog.h"
#include "Character.h"
#include "CharManager.h"
#include "Items.h"
#include "ItemManager.h"
#include "Users.h"
#include "UserManager.h"
#include "Channels.h"
#include "ChannelManager.h"
#include "Towns.h"
#include "TownManager.h"
#include "ItemModelManager.h"
#include "Message.h"
#include "CenterBankManager.h"
#include "VipCardManager.h"
#include "Tools.h"
#include "XMLData.h"
#include "GameDefine.h"
#include XMLDATA_MGR_PATH
#include LOGIC_MGR_PATH
#include LOG_MGR_PATH
#include PROTOCOLS_MGR_PATH
#include "OpcodesEx.h"
#include "WorldPacket.h"
#include "AIInterface.h"
#include "WSSocketManager.h"
#include "json/json.h"
#include "ProtocolDealEnums.h"
#include "url.h"
#include "GameDataEnum.h"


//===============================宠物数据操作===================================
bool CenterHappyFarmManager::AddCenterHappyFarm(CenterHappyFarm & chf)
{
	Fields fields;
	sDataMgr.initData(DataManager::DatabaseTypeCenter, DB_NAME_CENTERHAPPYFARM, &fields);
	
	fields["status"] = chf.status;					// 宠物状态
	fields["purchaser_pid"] = chf.purchaser_pid;	// 购买者PID
	fields["owner_pid"] = chf.owner_pid;			// 当前拥有者PID
	fields["owner_name"] = chf.owner_name;			// 购买者昵称
	fields["owner_head"] = chf.owner_head;			// 购买者头像
	
	fields["model_id"] = chf.model_id;				// 宠物模式ID
	fields["name"] = chf.name;						// 宠物名称
	fields["price"] = chf.price;					// 价格
	fields["ripe_coins"] = chf.ripe_coins;			// 成熟后获得的铜钱
	fields["born_time"] = chf.born_time;			// 出生时间
	fields["ripe_time"] = chf.ripe_time;			// 成熟时间
	
	fields["create_time"] = chf.create_time;		// 创建时间
	fields["end_time"] = chf.end_time;				// 结束时间
	
	if (!sDataMgr.insertData(DataManager::DatabaseTypeCenter, DB_NAME_CENTERHAPPYFARM, &fields))
		return false;
	
	chf.farm_id = fields["farm_id"].GetUInt32();
	return true;
}


bool CenterHappyFarmManager::UpdateCenterHappyFarm(const CenterHappyFarm & chf)
{
	Fields fields;
	fields["status"] = chf.status;					// 宠物状态
	// fields["purchaser_pid"] = chf.purchaser_pid;	// 购买者PID
	fields["owner_pid"] = chf.owner_pid;			// 当前拥有者PID
	// fields["owner_name"] = chf.owner_name;		// 购买者昵称
	// fields["owner_head"] = chf.owner_head;		// 购买者头像
	
	// fields["model_id"] = chf.model_id;			// 宠物模式ID
	// fields["name"] = chf.name;					// 宠物名称
	// fields["price"] = chf.price;					// 价格
	// fields["ripe_coins"] = chf.ripe_coins;		// 成熟后获得的铜钱
	fields["born_time"] = chf.born_time;			// 出生时间
	fields["ripe_time"] = chf.ripe_time;			// 成熟时间
	
	// fields["create_time"] = chf.create_time;		// 创建时间
	fields["end_time"] = chf.end_time;				// 结束时间
	
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_CENTERHAPPYFARM, 
													&fields, "`farm_id` = %u ", chf.farm_id);
	
	return count > 0;
}

#define SQLBUFER_LEN 16384

bool CenterHappyFarmManager::UpdateCenterHappyFarm(Fields * fields, const char * QueryString, ...)
{
	char sql[SQLBUFER_LEN] = ""; 
	va_list vlist; 
	va_start(vlist, QueryString); 
	vsnprintf(sql, SQLBUFER_LEN, QueryString, vlist); 
	va_end(vlist);
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_CENTERHAPPYFARM, fields, sql);
	return count > 0;
}

bool CenterHappyFarmManager::UpdateCenterHappyFarm(const uint32 &farm_id, Fields * fields)
{
	CenterHappyFarm cbf;
	GetCenterHappyFarm(farm_id, &cbf);
	
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_CENTERHAPPYFARM, fields, 
												"`farm_id` = %u", farm_id);
	
	return count > 0;
}


bool CenterHappyFarmManager::GetCenterHappyFarm(const uint32 & farm_id, CenterHappyFarm * cbf)
{
	assert (cbf);
	FieldRows rows;
	sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_CENTERHAPPYFARM, &rows, "`farm_id` = %u and status < 255", farm_id);
	if (rows.empty())
		return false;
	
	Fields fields = rows.front();
	
	cbf->farm_id = fields["farm_id"].GetUInt32();
	cbf->status = fields["status"].GetUInt8();
	cbf->purchaser_pid = fields["purchaser_pid"].GetUInt32();
	cbf->owner_pid = fields["owner_pid"].GetUInt32();
	cbf->owner_name = fields["owner_name"].GetValue();
	cbf->owner_head = fields["owner_head"].GetValue();
	
	cbf->model_id = fields["model_id"].GetUInt32();
	cbf->name = fields["name"].GetValue();
	cbf->price = fields["price"].GetUInt32();
	cbf->ripe_coins = fields["ripe_coins"].GetUInt32();
	cbf->born_time = fields["born_time"].GetUInt32();
	cbf->ripe_time = fields["ripe_time"].GetUInt32();
	
	cbf->create_time = fields["create_time"].GetValue();
	cbf->end_time = fields["end_time"].GetValue();
	
	return true;
}


uint32 CenterHappyFarmManager::GetCenterHappyFarmList(std::list<CenterHappyFarm> * lstData, const char * query,...)
{
	va_list argp;
	va_start(argp, query);
	lstData->clear();
	FieldRows fieldRows;
	
	char sql[SQLBUFER_LEN] = ""; 
	va_list vlist; 
	va_start(vlist, query); 
	vsnprintf(sql, SQLBUFER_LEN, query, vlist); 
	va_end(vlist);
	
	if (!sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_CENTERHAPPYFARM, &fieldRows, sql))
		return 0;
	
	FieldRows::iterator iter, enditer = fieldRows.end();
	for (iter = fieldRows.begin(); iter != enditer; ++ iter)
	{
		CenterHappyFarm cbf;
		Fields &fields = *iter;
		
		cbf.farm_id = fields["farm_id"].GetUInt32();
		cbf.status = fields["status"].GetUInt8();
		cbf.purchaser_pid = fields["purchaser_pid"].GetUInt32();
		cbf.owner_pid = fields["owner_pid"].GetUInt32();
		cbf.owner_name = fields["owner_name"].GetValue();
		cbf.owner_head = fields["owner_head"].GetValue();
		
		cbf.model_id = fields["model_id"].GetUInt32();
		cbf.name = fields["name"].GetValue();
		cbf.price = fields["price"].GetUInt32();
		cbf.ripe_coins = fields["ripe_coins"].GetUInt32();
		cbf.born_time = fields["born_time"].GetUInt32();
		cbf.ripe_time = fields["ripe_time"].GetUInt32();
		
		cbf.create_time = fields["create_time"].GetValue();
		cbf.end_time = fields["end_time"].GetValue();
		
		lstData->push_back(cbf);
	}
	
	return lstData->size();
}

//=============================宠物操作相关===================================
// 购买动物
bool CenterHappyFarmManager::BuyAnimal(UserPtr & pUser, const uint32 & model_id, const uint32 & num)
{
	if(pUser.isNull() || model_id == 0 || num == 0)
		return false;
	
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	if(pChr.isNull())
		return false;
	
WGS_CENTERHAPPYFARM_LOCK
	uint8 result = 0;
	
	// 获取农场动物配置
	const HappyFarm* pHf = sXmlDataMgr.GetHappyFarm(model_id);
	if(!pHf)
		return false;
	
	// 获取玩家自己的动物列表
	std::list<CenterHappyFarm> lstData;
	GetCenterHappyFarmList(&lstData, "`status` < 255 and `owner_pid` = %u", pUser->getUInt32Field("platform_id"));
	
	uint32 max_num = sXmlDataMgr.GetConfXMLValue("HF_MAX_ANIMAL");
	
	// 动物超过拥有上限
	if(lstData.size() + num > max_num)
		return false;
	
	WorldPacket packet;
	uint32 need_coins = pHf->price * num;
	if (sGLMgr.reduceItemNum(pChr, ItemModel_Coins, need_coins))
	{	
		// 铜钱变化日志
		sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_HappyFarm, ItemModel_Coins, en_UNT_Reduce, need_coins, pHf->model_id, num);	
		
		uint32 nt = time(0);
		for (uint32 i=0; i<num; ++i)
		{
			CenterHappyFarm chf;
			chf.status = enHappyFarmStatus_Alive;						// 宠物状态
			chf.purchaser_pid = pUser->getUInt32Field("platform_id");	// 购买者PID
			chf.owner_pid = pUser->getUInt32Field("platform_id");		// 当前拥有者PID
			chf.owner_name = pChr->getStringField("name");				// 购买者昵称
			chf.owner_head = pChr->getStringField("desc");				// 购买者头像
			
			chf.model_id = pHf->model_id;								// 宠物模式ID
			chf.name = pHf->szName;										// 宠物名称
			chf.price = pHf->price;										// 价格
			chf.ripe_coins = pHf->earnings;								// 成熟后获得的铜钱
			chf.born_time = nt;											// 出生时间
			chf.ripe_time = nt + 86400 * pHf->feeding_cycle;			// 成熟时间
			
			chf.create_time = sGLMgr.GetCurDateTime();					// 创建时间
			// chf.end_time = "";										// 结束时间（不创建）
			
			AddCenterHappyFarm(chf);									// 添加数据
			// 发送单个动物更新协议
			if (CreateSingleFarmPacket(&packet, chf))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
		}
		
		// 统计牧场动物变化日志
		String strFarms = GetPlayerAnimalsMap(pUser->getUInt32Field("platform_id"));
		HappyFarmBuySellLog(pUser, enHappyFarmLogSubType_Buy, model_id, pHf->szName, num, need_coins, strFarms);
	}
	
	// 发数据包	
	if (CreateBusinessHappyFarmPacket(&packet, result, enHappyFarmOp_Buy, model_id, pHf->szName, num, need_coins))
		sGLMgr.SendProtocolsToChr(pChr, &packet);
	
	return false;
}

// 添加动物（网关指令部分调用）
bool CenterHappyFarmManager::AddAnimal(UserPtr & pUser, const uint32 & model_id, const uint32 & num)
{
	if(pUser.isNull() || model_id == 0 || num == 0)
		return false;
	
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	if(pChr.isNull())
		return false;
	
WGS_CENTERHAPPYFARM_LOCK
	// 获取农场动物配置
	const HappyFarm* pHf = sXmlDataMgr.GetHappyFarm(model_id);
	if(!pHf)
		return false;
	
	// 获取玩家自己的动物列表
	std::list<CenterHappyFarm> lstData;
	GetCenterHappyFarmList(&lstData, "`status` < 255 and `owner_pid` = %u", pUser->getUInt32Field("platform_id"));
	
	uint32 max_num = sXmlDataMgr.GetConfXMLValue("HF_MAX_ANIMAL");
	
	// 动物超过拥有上限
	if(lstData.size() + num > max_num)
		return false;
	
	uint32 get_coins = num * pHf->price;
	
	WorldPacket packet;
	uint32 nt = time(0);
	for (uint32 i=0; i<num; ++i)
	{
		CenterHappyFarm chf;
		chf.status = enHappyFarmStatus_Alive;						// 宠物状态
		chf.purchaser_pid = pUser->getUInt32Field("platform_id");	// 购买者PID
		chf.owner_pid = pUser->getUInt32Field("platform_id");		// 当前拥有者PID
		chf.owner_name = pChr->getStringField("name");				// 购买者昵称
		chf.owner_head = pChr->getStringField("desc");				// 购买者头像
		
		chf.model_id = pHf->model_id;								// 宠物模式ID
		chf.name = pHf->szName;										// 宠物名称
		chf.price = pHf->price;										// 价格
		chf.ripe_coins = pHf->earnings;								// 成熟后获得的铜钱
		chf.born_time = nt;											// 出生时间
		chf.ripe_time = nt + 86400 * pHf->feeding_cycle;			// 成熟时间
		
		chf.create_time = sGLMgr.GetCurDateTime();					// 创建时间
		// chf.end_time = "";										// 结束时间（不创建）
		
		AddCenterHappyFarm(chf);									// 添加数据
		// 发送单个动物更新协议
		if (CreateSingleFarmPacket(&packet, chf))
			sGLMgr.SendProtocolsToChr(pChr, &packet);
	}
	
	// 统计牧场动物变化日志
	String strFarms = GetPlayerAnimalsMap(pUser->getUInt32Field("platform_id"));
	HappyFarmBuySellLog(pUser, enHappyFarmLogSubType_GwAdd, model_id, pHf->szName, num, get_coins, strFarms);
	return true;
}

// 出售动物
bool CenterHappyFarmManager::SellAnimal(UserPtr & pUser, const uint32 & farm_id)
{
	if(pUser.isNull() || farm_id == 0)
		return false;
	
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	if(pChr.isNull())
		return false;
	
WGS_CENTERHAPPYFARM_LOCK
	uint8 result = 0;
	
	CenterHappyFarm chf;
	if(!CenterHappyFarmManager::GetCenterHappyFarm(farm_id, &chf))
	{// 没有此动物
		return false;
	}
	
	if(chf.owner_pid != pUser->getUInt32Field("platform_id"))
	{// 不属于操作玩家
		return false;
	}
	
	if(chf.status == enHappyFarmStatus_Delete)
		return false;
	
	uint32 get_coins = chf.price;
	uint32 curr_time = time(0);
	if(curr_time >= chf.ripe_time)
	{// 成熟后额外获得铜钱
		get_coins += chf.ripe_coins;
	}
	
	// 增加铜钱，添加日志
	sGLMgr.addItemNum(pChr, ItemModel_Coins, get_coins);
	sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_HappyFarm, ItemModel_Coins, en_UNT_Add, get_coins, chf.model_id);
	
	chf.status = enHappyFarmStatus_Delete;
	chf.end_time = sGLMgr.GetCurDateTime();	// 设置宠物结束时间
	UpdateCenterHappyFarm(chf);
	
	// 统计牧场动物变化日志
	String strFarms = GetPlayerAnimalsMap(pUser->getUInt32Field("platform_id"));
	HappyFarmBuySellLog(pUser, enHappyFarmLogSubType_Sell, chf.model_id, chf.name, 1, get_coins, strFarms);
	
	// 发数据包
	WorldPacket packet;
	if (CreateBusinessHappyFarmPacket(&packet, result, enHappyFarmOp_Sell, chf.farm_id, chf.name, 1, get_coins))
		sGLMgr.SendProtocolsToChr(pChr, &packet);
	return true;
}

// 出售所有动物
void CenterHappyFarmManager::SellAllAnimals(UserPtr & pUser)
{
	if(pUser.isNull())
		return ;
	
	std::list<CenterHappyFarm> lstData;
	if(!GetCenterHappyFarmList(&lstData, "`status` < 255 and `owner_pid` = %u", pUser->getUInt32Field("platform_id")))
		return ;
	
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	if(pChr.isNull())
		return ;
	
	std::map<uint32, stFarmNameAndNum> mapFarmInfo;
	String farm_names = "";
	uint32 farm_coins = 0;
	std::list<CenterHappyFarm>::iterator iter, ei = lstData.end();
	for(iter = lstData.begin(); iter!=ei; ++iter)
	{
		farm_coins += (*iter).price;
		
		std::map<uint32, stFarmNameAndNum>::iterator fit = mapFarmInfo.find((*iter).model_id);
		if(fit == mapFarmInfo.end())
		{
			stFarmNameAndNum fnan;
			fnan.price = (*iter).price;
			fnan.num = 1;
			fnan.name = (*iter).name;
			mapFarmInfo.insert(std::make_pair((*iter).model_id, fnan));
		}
		else
		{
			fit->second.num++;
			fit->second.price += (*iter).price;
		}
		
		(*iter).status = enHappyFarmStatus_Delete;
		(*iter).end_time = sGLMgr.GetCurDateTime();	// 设置宠物结束时间
		UpdateCenterHappyFarm((*iter));
	}
	
	std::map<uint32, stFarmNameAndNum>::iterator itMap, eiMap = mapFarmInfo.end();
	for(itMap = mapFarmInfo.begin(); itMap!=eiMap; ++itMap)
	{
		char buf[256] = "";
		sprintf(buf, "%sx%u ", itMap->second.name.c_str(), itMap->second.num);
		farm_names += buf;
	}
	
	if(farm_coins)
	{
		uint32 pid = pUser->getUInt32Field("platform_id");
		
		std::map<uint32,uint32> mapItems;
		mapItems.insert(std::make_pair(ItemModel_Coins, farm_coins));
		
		String szTitle = "";
		String szContent = "";
		
		const MailModel * mailM = sXmlDataMgr.GetMailModel("SYSTEM_SELLFARM");
		if(mailM)
		{
			szTitle = mailM->szTitle;
			szContent = mailM->szContent;
			
			char buf[256] = "";
			// 亲爱的玩家：由于牧场功能改版，现将您原有宠物【%s】卖出，获得【%u】铜钱，请您收取！
			sprintf(buf, szContent.c_str(), farm_names.c_str(), farm_coins);
			
			szContent = buf;
		}
		
		sGLMgr.CreateMail(pid, szTitle, szContent, 0, en_ST_SystemSellFarm, &mapItems);
	}
	
}

// 赠送动物
bool CenterHappyFarmManager::TransAnimal(UserPtr & pUser, const uint32 & dest_pid, const uint32 & farm_id)
{
	if(pUser.isNull() || dest_pid == 0 || farm_id == 0)
		return false;
	
WGS_CENTERHAPPYFARM_LOCK
	
	if (pUser->getUInt32Field("platform_id") == dest_pid)
	{// 不能赠送给自己
		return false;
	}
	
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	if (pChr.isNull())
		return false;
	
	CenterHappyFarm chf;
	GameBank recvBank;
	uint8 result = enSendResult_Sucess;
	do
	{
		if (sXmlDataMgr.GetConfXMLValue("HAVE_VIP") && sVipCardMgr.GetUsedVipId(pChr) == 0)
		{// 验证是否需要检测VIP
			return false;
		}
		
		if(!CenterHappyFarmManager::GetCenterHappyFarm(farm_id, &chf))
		{// 没有此动物
			return false;
		}
		
		if(chf.owner_pid != pUser->getUInt32Field("platform_id"))
		{// 不属于操作玩家
			return false;
		}
		
		if(chf.status == enHappyFarmStatus_Delete)
			return false;
		
		if (!sBankMgr.GetPublicData(dest_pid, &recvBank))
		{
			result = enSendResult_ErrorPid;
			break;
		}
		
		std::list<CenterHappyFarm> lstData;
		GetCenterHappyFarmList(&lstData, "`status` < 255 and `owner_pid` = %u", dest_pid);
		
		uint32 max_num = sXmlDataMgr.GetConfXMLValue("HF_MAX_ANIMAL");
		if(max_num <= lstData.size())
		{
			result = enSendResult_OverLimit;
			break;
		}
		
	}while(0);
	
	WorldPacket packet;
	if (CreateGivingHappyFarmPacket(&packet, result, farm_id, dest_pid, recvBank.nick))
		sGLMgr.SendProtocolsToChr(pChr, &packet);
	
	if(result != enSendResult_Sucess)
		return false;
	
	// 更换拥有者
	chf.owner_pid = recvBank.platform_id;	
	chf.owner_name = recvBank.nick;			
	
	// 更新成熟时间
	chf.born_time = time(0);
	
	uint8 days = 7;
	const HappyFarm* pHf = sXmlDataMgr.GetHappyFarm(chf.model_id);
	if(pHf)
		days = pHf->feeding_cycle;
	
	chf.ripe_time = time(0) + 86400 * days;
	UpdateCenterHappyFarm(chf);
	
	String strGiveKucun = GetPlayerAnimalsMap(pUser->getUInt32Field("platform_id"));
	String strRecvKucun = GetPlayerAnimalsMap(recvBank.platform_id);
	HappyFarmGiveLog(pUser, chf, strGiveKucun);
	HappyFarmRecvLog(recvBank.platform_id, recvBank.nick, pUser, chf, strRecvKucun);
	
	// 如果玩家同服，且在线发送列表更新信息
	std::list<UserPtr> lstUser;
	sUserMgr.getUserList(&lstUser, 0, 1, "platform_id = %u", dest_pid);
	if(lstUser.size())
	{
		UserPtr pUser = *lstUser.begin();
		if(!pUser.isNull())
		{
			CharPtr pChr = sCharMgr.getByHandle(pUser->getUInt32Field("char_id"));
			if(pChr.isNull())
				return true;
			
			std::list<CenterHappyFarm> lstData;
			GetCenterHappyFarmList(&lstData, "`status` < 255 and `owner_pid` = %u", dest_pid);
			
			if(CreateMyHappyFarmPacket(&packet, lstData))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
		}
	}
	
	return true;
}

// 获得当前玩家宠物库存
String CenterHappyFarmManager::GetPlayerAnimalsMap(const uint32 & pid)
{
	std::list<CenterHappyFarm> lstData;
	GetCenterHappyFarmList(&lstData, "`status` < 255 and `owner_pid` = %u", pid);
	
	std::map<uint32, HappyFarm> mapXml;
	uint32 total_farm_num = sXmlDataMgr.GetHappyFarmList(mapXml);
	
	// 初始库存宠物map结构
	std::map<uint32, uint32> mapCurrFarms;
	for(uint32 i=0; i<total_farm_num; ++i)
	{
		mapCurrFarms.insert(std::make_pair(i+1, 0));
	}
	
	std::list<CenterHappyFarm>::iterator iter,ei = lstData.end();
	for(iter = lstData.begin(); iter!=ei; ++iter)
	{
		std::map<uint32, uint32>::iterator fit = mapCurrFarms.find((*iter).model_id);
		if(fit == mapCurrFarms.end())
		{// 未找到记录
			mapCurrFarms.insert(std::make_pair((*iter).model_id, 1));
		}
		else
		{// 找到记录
			fit->second++;
		}
	}
	
	Json::Value val;
	
	std::map<uint32,uint32>::iterator itMI, eiMI = mapCurrFarms.end();
	for(itMI = mapCurrFarms.begin(); itMI!=eiMI; ++itMI)
	{
		val[StringConverter::toString(itMI->first)] = itMI->second;
	}
	
	Log.Debug("CenterHappyFarmManager::GetPlayerAnimalsMap","user pid[%u] map size[%u]", pid, mapCurrFarms.size());
	
	Json::FastWriter w;
	return w.write(val);
}

// 获得玩家宠物列表
void CenterHappyFarmManager::GetHappyFarmList(UserPtr & pUser)
{
	if(pUser.isNull())
		return ;
	
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	if(pChr.isNull())
		return ;
	
	std::list<CenterHappyFarm> lstData;
	GetCenterHappyFarmList(&lstData, "`status` < 255 and `owner_pid` = %u", pUser->getUInt32Field("platform_id"));
	
	WorldPacket packet;
	if(CreateMyHappyFarmPacket(&packet, lstData))
		sGLMgr.SendProtocolsToChr(pChr, &packet);
}

//===============================协议相关=============================
//-------------------------------------------------------------------
bool 	CenterHappyFarmManager::CreateMyHappyFarmPacket(WorldPacket *packet, std::list<CenterHappyFarm> &pList)
{
	packet->clear();
	packet->SetOpcode(SMSG_GETPRAIRIE_LIST);
	*packet << uint16(SMSG_GETPRAIRIE_LIST) << uint16(0);	
	*packet << uint8(pList.size());
	uint32 nt = time(0);
	std::list<CenterHappyFarm>::iterator iter, ei = pList.end();
	for (iter = pList.begin(); iter != ei; ++iter)
	{
		const HappyFarm* pHf = sXmlDataMgr.GetHappyFarm((*iter).model_id);
		if (!pHf)
			return false;
		
		*packet << uint32((*iter).farm_id);
		*packet << uint8((*iter).model_id);
		AppendPacketString<uint8>(packet, (*iter).name);
		*packet << uint32(nt);
		*packet << uint32((*iter).born_time);
		*packet << uint32((*iter).ripe_time);
		*packet << uint32(pHf->price);
		*packet << uint32(pHf->earnings);
	}
	
	packet->SetLength(packet->size());
	return true;
}
//-------------------------------------------------------------------
bool 	CenterHappyFarmManager::CreateBusinessHappyFarmPacket(WorldPacket *packet, uint8 result, uint8 type, 
									const uint32 &farmId, const String &strName, uint16 number, uint32 getCoins)
{
	packet->clear();
	packet->SetOpcode(SMSG_HAPPYPRAIRIE_BUY);
	*packet << uint16(SMSG_HAPPYPRAIRIE_BUY) << uint16(0);	
	*packet << uint8(result);
	*packet << uint8(type);
	*packet << farmId;
	AppendPacketString<uint8>(packet, strName);
	*packet << uint16(number);
	*packet << uint32(getCoins);
	packet->SetLength(packet->size());
	return true;
}
//-------------------------------------------------------------------
bool 	CenterHappyFarmManager::CreateGivingHappyFarmPacket(WorldPacket *packet, uint8 result, uint32 farmId, uint32 destPId, String strNick)
{
	packet->clear();
	packet->SetOpcode(SMSG_GIVE_PRAIRIE);
	*packet << uint16(SMSG_GIVE_PRAIRIE) << uint16(0);	
	*packet << uint8(result);
	*packet << uint32(farmId);
	*packet << uint32(destPId);
	AppendPacketString<uint8>(packet, strNick);	
	packet->SetLength(packet->size());
	return true;
}
//-------------------------------------------------------------------
bool 	CenterHappyFarmManager::CreateGivingRecodePacket(WorldPacket *packet, uint32 platformId)
{	
	packet->clear();
	packet->SetOpcode(SMSG_GIVE_PRAIRIE_RECORD);
	*packet << uint16(SMSG_GIVE_PRAIRIE_RECORD) << uint16(0);	
	std::list<GameLog> lstGameLogs;
	char strSql[512] = "";
	sprintf(strSql, "UNIX_TIMESTAMP(create_time) >= %u AND `src_id` = %u AND `type` = %u order by `create_time` DESC", 
			uint32(time(0)-sXmlDataMgr.GetConfXMLValue("HF_RECODE_TIME")), platformId, en_Operate_HappyFarmNew);			
	
	sChannelMgr.getRawCenterLogList(&lstGameLogs, 0, sXmlDataMgr.GetConfXMLValue("HF_RECODE_COUNT"), strSql);
	
	
	*packet << uint8(lstGameLogs.size());
	std::list<GameLog>::iterator iter, enditer = lstGameLogs.end();
	for (iter = lstGameLogs.begin(); iter != enditer; ++ iter)
	{
		GameLog &log = *iter;
		uint8 sub_type = log.sub_type > 0 ? log.sub_type - 1 : 0;
		
		*packet << uint8(sub_type)								// 日志类型
				<< uint32(log.dest_id);							// 赠送或者获赠玩家PID（买卖没有此项）
		AppendPacketString<uint8>(packet, log.sdata1);			// 赠送或者获赠玩家昵称（买卖没有此项）
		*packet << (uint8)log.data4;							// 宠物类型
		AppendPacketString<uint8>(packet, log.sdata7);			// 宠物名称
		*packet << uint16(log.data2);							// 宠物数量
		*packet << uint32(log.data3);							// 铜钱
		AppendPacketString<uint8>(packet, log.create_time);		// 日志创建时间
	}
	
	packet->SetLength(packet->size());
	return true;
}
//-------------------------------------------------------------------
bool 	CenterHappyFarmManager::CreateBuyFarmListPacket(WorldPacket *packet)
{
	packet->clear();
	packet->SetOpcode(SMSG_BUYHAPPYFARM_LIST);
	*packet << uint16(SMSG_BUYHAPPYFARM_LIST) << uint16(0);	
	
	std::map<uint32, HappyFarm> mapHappyFarm;
	sXmlDataMgr.GetHappyFarmList(mapHappyFarm);
	*packet << uint8(mapHappyFarm.size());
	
	std::map<uint32, HappyFarm>::iterator mapi, endmapi = mapHappyFarm.end();
	for (mapi = mapHappyFarm.begin(); mapi != endmapi; ++ mapi)
	{
		*packet << (uint8)mapi->second.model_id
				<< (uint32)mapi->second.price
				<< (uint8)mapi->second.feeding_cycle
				<< (uint32)mapi->second.earnings;
		
		AppendPacketString<uint8>(packet, mapi->second.szName);
	}
	
	packet->SetLength(packet->size());
	return true;
}
//-------------------------------------------------------------------
bool 	CenterHappyFarmManager::CreateSingleFarmPacket(WorldPacket *packet, const CenterHappyFarm &chf)
{
	packet->clear();
	packet->SetOpcode(SMSG_SINGLEHAPPYFARM_LIST);
	*packet << uint16(SMSG_SINGLEHAPPYFARM_LIST) << uint16(0);	
	const HappyFarm* pHf = sXmlDataMgr.GetHappyFarm(chf.model_id);
	if (!pHf)
		return false;
	
	uint32 nt = time(0);
	*packet << uint32(chf.farm_id)
			<< uint8(chf.model_id);
	
	AppendPacketString<uint8>(packet, chf.name);
	*packet << uint32(nt)
			<< uint32(chf.born_time)
			<< uint32(chf.ripe_time)
			<< uint32(pHf->price)
			<< uint32(pHf->earnings);
	
	packet->SetLength(packet->size());
	return true;
}

//==================================日志相关=========================================
//宠物买卖日志
bool CenterHappyFarmManager::HappyFarmBuySellLog(UserPtr &pUser, 
												const uint8 &opType,
												const uint32 &model_id,
												const String &szName, 
												const uint32 &num, 
												const uint32 &coins, 
												String strKucun)
{
	if(pUser.isNull())
		return false;
	
	GameLog *pLog = sChannelMgr.newDumyCenterLog();
	if(NULL == pLog)
	{
		sChannelMgr.freeDumyLog(pLog);
		return false;
	}
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	pLog->status = 1;
	pLog->type = en_Operate_HappyFarmNew;
	pLog->sub_type = opType;
	pLog->src_id= pid;
	
	pLog->platform_id = pid;
	pLog->user_name = pUser->getStringField("name");	// 用户Session
	pLog->user_nick = pUser->getStringField("nick");	// 昵称
	pLog->user_ip = pUser->getStringField("ip");		// IP地址
	pLog->user_addr = pUser->getStringField("addr");	// 地址
	
	pLog->data1 = 0;									// 宠物ID
	pLog->data2 = num;									// 操作数量
	pLog->data3 = coins;								// 铜钱（根据sub_type来判断正负）
	pLog->data4 = model_id;								// 宠物模式ID
	
	pLog->sdata7 = szName;								// 宠物名称
	pLog->sdata8 = strKucun;							// 当前库存
	
	pLog->create_time = sTools.GetCurDateTime();
	sChannelMgr.addCenterLogDB(pLog);
	sChannelMgr.freeDumyCenterLog(pLog);
	Log.Debug("CenterHappyFarmManager::HappyFarmBuySellLog","user[%u] pid[%u] opType[%u]", pUser->getHandle(), pid, opType);
	return true;
}

//宠物赠送日志
bool CenterHappyFarmManager::HappyFarmGiveLog(UserPtr &pGiveUser, CenterHappyFarm & chf, String strKucun)
{
	if(pGiveUser.isNull())
		return false;
	
	GameLog *pLog = sChannelMgr.newDumyCenterLog();
	if(NULL == pLog)
	{
		sChannelMgr.freeDumyLog(pLog);
		return false;
	}
	
	uint32 pid = pGiveUser->getUInt32Field("platform_id");
	
	pLog->status = 1;
	pLog->type = en_Operate_HappyFarmNew;
	pLog->sub_type = enHappyFarmLogSubType_Give;
	pLog->src_id= pid;									// 赠送方PID
	pLog->dest_id= chf.owner_pid;						// 获赠方PID
	
	pLog->platform_id = pid;
	pLog->user_name = pGiveUser->getStringField("name");// 用户Session
	pLog->user_nick = pGiveUser->getStringField("nick");// 昵称
	pLog->user_ip = pGiveUser->getStringField("ip");	// IP地址
	pLog->user_addr = pGiveUser->getStringField("addr");// 地址
	
	pLog->data1 = chf.farm_id;							// 宠物ID
	pLog->data2 = 1;									// 操作数量
	pLog->data3 = chf.price;							// 宠物价值
	pLog->data4 = chf.model_id;							// 宠物模式ID
	
	pLog->sdata1 = chf.owner_name;						// 目标玩家昵称
	pLog->sdata7 = chf.name;							// 宠物名称
	pLog->sdata8 = strKucun;							// 当前库存
	
	pLog->create_time = sTools.GetCurDateTime();
	sChannelMgr.addCenterLogDB(pLog);
	sChannelMgr.freeDumyCenterLog(pLog);
	Log.Debug("CenterHappyFarmManager::HappyFarmGiveLog","user[%u] pid[%u]", pGiveUser->getHandle(), pid);
	return true;
}

//宠物获赠日志
bool CenterHappyFarmManager::HappyFarmRecvLog(const uint32 &recv_pid, String &recv_name, UserPtr &pGiveUser, CenterHappyFarm & chf, String strKucun)
{
	if(pGiveUser.isNull())
		return false;
	
	GameLog *pLog = sChannelMgr.newDumyCenterLog();
	if(NULL == pLog)
	{
		sChannelMgr.freeDumyLog(pLog);
		return false;
	}

	pLog->status = 1;
	pLog->type = en_Operate_HappyFarmNew;
	pLog->sub_type = enHappyFarmLogSubType_Recv;
	pLog->src_id= recv_pid;									 // 获赠方PID
	pLog->dest_id = pGiveUser->getUInt32Field("platform_id");// 赠送方PID
	
	pLog->platform_id = recv_pid;
	pLog->user_nick = recv_name;							// 昵称
	
	pLog->data1 = chf.farm_id;								// 宠物ID
	pLog->data2 = 1;										// 操作数量
	pLog->data3 = chf.price;								// 宠物价值
	pLog->data4 = chf.model_id;								// 宠物模式ID
	
	pLog->sdata1 = pGiveUser->getStringField("nick");		// 目标玩家昵称
	pLog->sdata7 = chf.name;								// 宠物名称
	pLog->sdata8 = strKucun;								// 当前库存
	
	pLog->create_time = sTools.GetCurDateTime();
	sChannelMgr.addCenterLogDB(pLog);
	sChannelMgr.freeDumyCenterLog(pLog);
	Log.Debug("CenterHappyFarmManager::HappyFarmRecvLog","user pid[%u]", recv_pid);
	return true;
}

// 将json格式的牧场数据转换为牧场数据库存储
void CenterHappyFarmManager::TranJsonDataToNewHappyFarm(UserPtr & pUser)
{
	if(pUser.isNull())
		return ;
	
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	if(pChr.isNull())
		return ;
	
	// 玩家公共数据
	GameBank bank;
	sBankMgr.GetPublicData(pUser, &bank);
	
	// 宠物列表
	std::list<HappyFarmItem> lstHFI;
	sBankMgr.HappyFarmJsonToStruct(bank.sdata2, &lstHFI);
	
	if(lstHFI.empty())
		return ;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	// 遍历宠物列表
	std::list<HappyFarmItem>::iterator iter, enditer = lstHFI.end();
	for (iter = lstHFI.begin(); iter != enditer; ++ iter)
	{
		HappyFarmItem &hfi = *iter;
		const HappyFarm *pHf = sXmlDataMgr.GetHappyFarm(hfi.model_id);
		if(!pHf)
			continue;
		
		CenterHappyFarm chf;
		chf.status = 1;									// 宠物状态
		chf.purchaser_pid = pid;						// 购买者PID
		chf.owner_pid = pid;							// 当前拥有者PID
		chf.owner_name = pChr->getStringField("name");	// 购买者昵称
		chf.owner_head = pChr->getStringField("desc");	// 购买者头像
		
		chf.model_id = hfi.model_id;					// 宠物模式ID
		chf.name = pHf->szName;							// 宠物名称
		chf.price = pHf->price;							// 价格
		chf.ripe_coins = pHf->earnings;					// 成熟后获得的铜钱
		chf.born_time = hfi.begin_time;					// 出生时间
		chf.ripe_time = hfi.end_time;					// 成熟时间
		
		chf.create_time = sGLMgr.GetCurDateTime();		// 日志创建时间
		
		AddCenterHappyFarm(chf);						// 添加记录
	}
	
	bank.sdata2 = "";
	sBankMgr.SaveHappyFarmDB(bank);						// 清除原来宠物数据
}

